import shutil
import sys
import os
import xlrd
import re
import codecs

if sys.getdefaultencoding() != 'utf-8':
    sys.setdefaultencoding('utf-8')

curpath = os.path.dirname(os.path.abspath(sys.argv[0]))

lua_file_head_format_desc = '''--[[

        %s
        exported by excel2lua.py
        from file:%s

--]]\n\n'''


def excel2lua(src_excel_path, tgt_lua_path):
    print('[file] %s -> %s' % (src_excel_path, tgt_lua_path))
    # load excel data
    excel_data_src = xlrd.open_workbook(src_excel_path, encoding_override='utf-8')
    print('[excel] Worksheet name(s):', excel_data_src.sheet_names())
    excel_sheet = excel_data_src.sheet_by_index(0)
    print('[excel] parse sheet: %s (%d row, %d col)' % (excel_sheet.name, excel_sheet.nrows, excel_sheet.ncols))

    # excel data dict
    excel_data_dict = {}

    # col name list
    col_name_list = []

    # col val type list
    col_val_type_list = []

    # ctype: 0 empty, 1 string, 2 number, 3 date, 4 boolean, 5 error

    headFirst = excel_sheet.cell(0, 0)
    headStr = headFirst.value
    headArr = headStr.split("|")
    idNum = 1
    if len(headArr) > 1:
        idNum = int(headArr[1])
    print(idNum)
    print("------")

    for col in range(0, excel_sheet.ncols):
        cell = excel_sheet.cell(1, col)
        col_name_list.append(str(cell.value))

    for col in range(0, excel_sheet.ncols):
        cell = excel_sheet.cell(2, col)
        col_val_type_list.append(str(cell.value))

    excel_id_list = []
    for row in range(3, excel_sheet.nrows):
        cell_id = excel_sheet.cell(row, 0).value
        if idNum > 1:
            cell_id = ""
            for i in range(idNum):
                if i == (idNum - 1):
                    cell_id = cell_id + str(int(excel_sheet.cell(row, i).value))
                else:
                    cell_id = cell_id + str(int(excel_sheet.cell(row, i).value)) + "_"

        if cell_id in excel_data_dict:
            print('[warning] duplicated data id: "%d", all previous value will be ignored!~' % (cell_id))

        # row data list
        row_data_list = []

        for col in range(0, excel_sheet.ncols):
            cell = excel_sheet.cell(row, col)
            k = col_name_list[col]
            cell_val_type = col_val_type_list[col]

            # ignored the string that start with '_'
            if str(k).startswith('_'):
                continue

            if cell_val_type == 'string':
                if cell.ctype == 0:
                    v = '\'\''
                else:
                    v = '\'%s\'' % str((cell.value))
            elif cell_val_type == 'int':
                if cell.ctype == 0:
                    v = -1
                else:
                    v = int(cell.value)
            elif cell_val_type == 'float':
                if cell.ctype == 0:
                    v = -1
                else:
                    v = float(cell.value)
            elif cell_val_type == 'table':
                if cell.ctype == 0:
                    v = '{}'
                else:
                    v = cell.value
            else:
                v = cell.value

            row_data_list.append([k, v])

        excel_data_dict[cell_id] = row_data_list
        excel_id_list.append(cell_id)

    searchObj = re.search(r'([^\\/:*?"<>|\r\n]+)\.\w+$', tgt_lua_path, re.M | re.I)
    lua_table_name = searchObj.group(1)

    src_excel_file_name = os.path.basename(src_excel_path)
    tgt_lua_file_name = os.path.basename(tgt_lua_path)

    # file head desc
    lua_file_head_desc = lua_file_head_format_desc % (tgt_lua_file_name, src_excel_file_name)

    # export to lua file
    lua_export_file = codecs.open(tgt_lua_path, 'w', 'utf-8')
    lua_export_file.write(lua_file_head_desc)

    cellIndex = 1
    idmaps = {}
    #
    lua_export_file.write('local _data = {\n')
    for k in excel_id_list:
        v = excel_data_dict[k]
        lua_export_file.write('  [{0}] '.format(cellIndex) + '= {')
        idmaps[k] = cellIndex
        cellIndex = cellIndex + 1
        for row_data in v:
            lua_export_file.write('{0} = {1},'.format(row_data[0], row_data[1]))
            print(row_data[1])
        lua_export_file.write('},\n')

    lua_export_file.write('}\n\n')
    #

    # 
    lua_export_file.write('local id_to_index={\n')
    for k in excel_id_list:
        v = idmaps[k]
        if isinstance(k, float):
            lua_export_file.write('   [{0}] = {1},\n'.format(int(k), v))
        elif isinstance(k, int):
            lua_export_file.write('   [{0}] = {1},\n'.format(int(k), v))
        else:
            lua_export_file.write("   ['{0}'] = {1},\n".format(k, v))
    lua_export_file.write('}\n\n')
    # 

    #
    lua_export_file.write('local %s={}\n\n' % lua_table_name)
    lua_export_file.write('function {0}.length() \n   return #_data \nend \n\n'.format(lua_table_name))
    lua_export_file.write('function {0}.indexOf(index) \n   return _data[index] \nend \n\n'.format(lua_table_name))
    if idNum == 1:
        lua_export_file.write(
            'function {0}.get(id) \n  return {1}.indexOf(id_to_index[id])\nend \n\n'.format(lua_table_name,
                                                                                            lua_table_name))
    else:
        param = ""
        indexKey = ""
        for i in range(idNum):
            if i == idNum - 1:
                indexKey = indexKey + "value" + str(i)
                param = param + "value" + str(i)
            else:
                param = param + "value" + str(i) + ","
                indexKey = indexKey + "value" + str(i) + "..'_'.."
        print(param)
        print(indexKey)
        lua_export_file.write(
            'function {0}.get({1}) \n  return {2}.indexOf(id_to_index[{3}])\nend \n\n'.format(lua_table_name,
                                                                                              param, lua_table_name,
                                                                                              indexKey
                                                                                              ))
    lua_export_file.write('return %s' % lua_table_name)
    #

    lua_export_file.close()

    print('[excel] %d row data exported!~' % (excel_sheet.nrows))


# ~$
striii = "~$hahahah"
striii.find("~$")
if __name__ == '__main__':

    xlsxPath = curpath + "/xlsx"
    dirList = os.listdir(xlsxPath)

    for fileName in dirList:
        if os.path.isfile(xlsxPath + "/" + fileName):
            retIndex = fileName.find("~$")
            if retIndex == -1:
                realName = fileName.split(".")
                realName = realName[0]
                excel2lua(os.path.join(curpath + "/xlsx", fileName), os.path.join(curpath + "/lua", realName + ".lua"))
                shutil.copy(os.path.join(curpath + "/lua", realName + ".lua"),
                            os.path.join(curpath + "/../Assets/LuaScripts/config", realName + ".lua"))
        else:
            pass

    os.system("pause")
